<template>
  <div class="inner-warp">
    <MainTitleVue title="个人信息" />
    <div class="sub-warp">
      <div align="center">
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-avatar round :size="80" :src="data.avatar" @click="showChangeAvatar = true"></n-avatar>
          </template>
          修改头像
        </n-tooltip>
      </div>
      <n-divider></n-divider>
      <div align="center" class="detail-bar">
        <span style="font-weight: bold;">账号：</span>
        <n-text>{{ data.acc }}</n-text>
      </div>
      <div align="center" class="detail-bar">
        <span style="font-weight: bold;">昵称：</span>
        <n-text>{{ data.name }}</n-text>
      </div>
      <n-divider title-placement="center">
        <n-button
          round
          color="#333333"
          size="small"
          @click="showChangeInfo = true; changedName = data.name; changedAcc = ''; vercode = ''"
        >修改信息</n-button>
        <n-divider vertical />
        <n-button
          round
          color="#333333"
          size="small"
          @click="showChangePwd = true; changedPwd = ''; repeatPwd = '';"
        >修改密码</n-button>
      </n-divider>
      <!-- 修改头像 -->
      <n-modal
        class="custom-card"
        v-model:show="showChangeAvatar"
        preset="card"
        title="修改头像"
        size="huge"
        style="width: 700px;"
        :bordered="false"
      >
        <div class="picchart">
          <div
            class="uploadPic"
            @dragover="filedragover"
            @drop="filedrop"
            v-show="img.length === 0"
          >
            <input
              label="本地头像上传"
              accept="image/*"
              type="file"
              id="file"
              class="imginput"
              ref="imgfile"
              @change="selectImg"
            />
          </div>
          <div class="preview" v-for="(item,index) in img" :key="index" v-show="img.length !== 0">
            <img :src="item" alt="头像预览" class="previewPic" />
            <div class="delet" @click="delet(index)">x</div>
          </div>
        </div>
        <template #footer>
          <n-button color="#333333" class="modal-btn" @click="comfirmAvatarChange">确认</n-button>
          <n-button class="modal-btn" @click="cancelAvatarChange">取消</n-button>
        </template>
      </n-modal>
      <!-- 修改密码 -->
      <n-modal
        class="custom-card"
        v-model:show="showChangePwd"
        preset="card"
        title="修改密码"
        size="huge"
        style="width: 600px;"
        :bordered="false"
      >
        <n-input
          type="password"
          v-model:value="oldPwd"
          placeholder="旧密码"
          clearable
          show-password-on="mousedown"
          size="small"
          style="max-width: 100%;"
        >{{ oldPwd }}</n-input>
        <n-input
          type="password"
          v-model:value="changedPwd"
          placeholder="新密码"
          clearable
          size="small"
          show-password-on="mousedown"
          style="max-width: 100%;margin-top: 15px;"
        >{{ changedPwd }}</n-input>
        <n-input
          type="password"
          v-model:value="repeatPwd"
          placeholder="重复密码"
          clearable
          size="small"
          show-password-on="mousedown"
          style="max-width: 100%;margin-top: 15px;"
        >{{ repeatPwd }}</n-input>
        <template #footer>
          <n-button color="#333333" class="modal-btn" @click="comfirmPwdChange">确认</n-button>
          <n-button class="modal-btn" @click="cancelPwdChange">取消</n-button>
        </template>
      </n-modal>
      <!-- 修改信息 -->
      <n-modal
        class="custom-card"
        v-model:show="showChangeInfo"
        preset="card"
        title="修改信息"
        size="huge"
        style="width: 600px;"
        :bordered="false"
      >
        <n-divider title-placement="left">修改昵称</n-divider>
        <n-input
          type="text"
          v-model:value="changedName"
          placeholder="新昵称"
          maxlength="30"
          show-count
          clearable
          size="small"
          style="max-width: 79%;"
        >{{ changedName }}</n-input>
        <n-button class="info-btn" size="small" @click="saveName" color="#333333">保存</n-button>
        <n-button class="info-btn2" size="small" @click="cancelName">取消</n-button>
        <n-divider title-placement="left">修改邮箱</n-divider>
        <n-input
          type="text"
          v-model:value="changedAcc"
          placeholder="新邮箱"
          clearable
          size="small"
          style="max-width: 80%;"
        >{{ changedAcc }}</n-input>
        <n-button class="info-btn2" size="small" @click="sendVarcode" v-show="!isSent">发送验证码</n-button>
        <n-button class="info-btn2" size="small" disabled v-show="isSent">已发送&nbsp;{{ sendTime }}s</n-button>
        <n-input
          type="text"
          v-model:value="vercode"
          placeholder="验证码"
          clearable
          size="small"
          style="max-width: 30%;margin-top: 12px;"
        >{{ changedAcc }}</n-input>
        <n-button class="info-btn3" size="small" @click="changeAcc" color="#333333">更改邮箱</n-button>
        <template #footer>
          <n-button color="#333333" class="modal-btn" @click="comfirmInfoChange">确认</n-button>
          <n-button class="modal-btn" @click="cancelInfoChange">取消</n-button>
        </template>
      </n-modal>
    </div>
  </div>
</template>

<script setup lang='ts'>
import MainTitleVue from "@/components/common/MainTitle.vue";
import { onMounted, getCurrentInstance, ref } from "vue";
import { useMessage } from "naive-ui";
import { userinfo } from '@/utils/userinfo'

// api访问代理
const { proxy } = getCurrentInstance() as any

// 引入消息函数
const message = useMessage()

// 修改头像模态框
const showChangeAvatar = ref(false)
// 修改密码模态框
const showChangePwd = ref(false)
// 修改信息模态框
const showChangeInfo = ref(false)

//新上传的头像
const img = ref([])
let imgfile = ref(null)

onMounted(() => {
  init()
})

let data = ref({
  acc: 'test@buaa.edu.cn',
  name: '七海7nanami',
  avatar: ''
})

// 在修改信息弹窗里的变量
const changedName = ref(data.value.name)
const changedAcc = ref("")
const oldPwd = ref("")
const changedPwd = ref("")
const repeatPwd = ref("")
// 在修改信息弹窗里，发送验证码相关的变量
var isSent = ref(false)
var sendTime = ref(60)
var vercode = ref("")

const init = (() => {
  proxy.$api.user.getUserInfo().then((result: any) => {
    if (result.success) {
      data.value = result.data
    } else {
      message.warning(result.msg)
    }
  }).catch(() => {
    message.error('未知错误')
  });
})

//预览头像图片
const selectImg = ((e: any) => {
  console.log(img.value.length)
  if (e.target.files.length > 1) {
    message.warning("只能选取一张图片");
    return;
  }
  if (e.target.files.size / 1024 / 1024 >= 5) {
    message.warning("图片大小太大");
    return;
  }
  for (let item of e.target.files) {
    let reader = new FileReader();
    reader.readAsDataURL(item);
    reader.addEventListener("load", function () {
      (img.value as any).push(this.result as any);
    });
  }
})

//删除现在上传的图片（来重新上传）
const delet = ((index: number) => {
  img.value.splice(index, 1);
})

const filedragover = ((e: any) => {
  e.preventDefault();
})

const filedrop = ((e: any) => {
  e.preventDefault();
  const file = e.dataTransfer.files[0]
  console.log(file)
  console.log('拖拽释放鼠标时')

  if (!file) return

  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.addEventListener("load", function () {
    (img.value as any).push(this.result as any);
  });
  console.log(imgfile);
  console.log(img);
})

// 确认头像修改
const comfirmAvatarChange = (() => {
  let dataurl = img.value[0];
  proxy.$api.user.uploadPortrait({ img: dataurl }).then((result: any) => {
    if (result.success) {
      message.success("修改成功");
      userinfo.avatar = dataurl;
      showChangeAvatar.value = false;
      init()
    } else {
      message.warning(result.msg);
    }
  }).catch(() => {
    message.error('未知错误')
  })
})

// 取消头像修改
const cancelAvatarChange = (() => {
  showChangeAvatar.value = false
})

// 确认密码修改
const comfirmPwdChange = (() => {
  if (!oldPwd.value) {
    message.warning('请输入旧密码')
  }
  if (!changedPwd.value) {
    message.warning('请输入新密码')
  } else if (!/^(\w){6,20}$/.test(changedPwd.value)) {
    message.warning('密码应为6~20位，只包含字母、数字或下划线')
  }
  else if (changedPwd.value != repeatPwd.value) {
    message.warning('重复密码错误')
  }
  else {
    proxy.$api.user.changeUserPwd({ old_pwd: oldPwd.value, new_pwd: changedPwd.value }).then((result: any) => {
      if (result.success) {
        message.success("修改成功")
        showChangePwd.value = false
      } else {
        message.warning(result.msg)
      }
    }).catch(() => {
      message.error('未知错误')
    });
  }
})

// 取消密码修改
const cancelPwdChange = (() => {
  showChangePwd.value = false
})

// 确认信息修改
const comfirmInfoChange = (() => {
  showChangeInfo.value = false
})

// 取消信息修改
const cancelInfoChange = (() => {
  showChangeInfo.value = false
})

// 保存昵称修改
const saveName = (() => {
  proxy.$api.user.changeUserName({ new_name: changedName.value }).then((result: any) => {
    if (result.success) {
      message.success("保存成功")
      userinfo.user_name = changedName.value
      data.value.name = changedName.value
    } else {
      message.warning(result.msg)
    }
  }).catch(() => {
    message.error('未知错误')
  });
})

// 取消昵称修改
const cancelName = (() => {
  changedName.value = data.value.name
})

// 发送验证码
const sendVarcode = (() => {
  if (!changedAcc.value) {
    message.warning("请输入新邮箱");
  }
  else if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(changedAcc.value)) {
    message.warning("新邮箱格式错误")
  }
  else {
    isSent.value = true;
    var verCodeTime = setInterval(() => {
      sendTime.value--;
    }, 1000);
    setTimeout(() => {
      clearInterval(verCodeTime);
      sendTime.value = 60;
      isSent.value = false;
    }, 60000);
    proxy.$api.user.sendVercode({ new_acc: changedAcc.value }).then((result: any) => {
      if (result.success) {
        message.success("发送成功")
      } else {
        message.warning(result.msg)
      }
    }).catch(() => {
      message.error('未知错误')
    });
  }
})

// 更改邮箱
const changeAcc = (() => {
  if (!changedAcc) {
    message.warning("请输入新邮箱");
  }
  else if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(changedAcc.value)) {
    message.warning("新邮箱格式错误")
  }
  else if (!vercode.value) {
    message.warning("请输入验证码")
  }
  else {
    proxy.$api.user.changeUserAcc({ new_acc: changedAcc.value, vercode: vercode.value }).then((result: any) => {
      if (result.success) {
        message.success("更改成功")
        data.value.acc = changedAcc.value
      } else {
        message.warning(result.msg)
      }
    }).catch(() => {
      message.error('未知错误')
    });
  }
})
</script>

<style scoped>
.inner-warp {
  margin: 50px auto;
  width: 1100px;
}

.sub-warp {
  margin: 3% 13%;
}

.detail-bar {
  font-size: large;
  margin: 10px auto;
}

.n-avatar:hover {
  cursor: pointer;
  filter: gray;
  -moz-opacity: 0.8;
  opacity: 0.8;
}

.modal-btn {
  float: right;
  margin-left: 10px;
}
.info-btn {
  float: right;
  margin-left: 5px;
}
.info-btn2 {
  float: right;
}
.info-btn3 {
  margin-left: 15px;
}

.picchart {
  margin: 10%, 5%, 5%, 10%;
  height: 400px;
  width: 800px;
}
.preview {
  width: 100%;
  height: 100%;
}

.uploadPic {
  height: 100%;
  width: 76%;
  border: 1px solid #ccc;
  background: #f9f9f9;
}

.imginput {
  position: absolute;
  left: 38%;
  top: 45%;
}

.delet {
  position: absolute;
  right: 6%;
  top: 14.5%;
  width: 25px;
  height: 23px;
  text-align: center;
  line-height: 20px;
  font-size: 15px;
  background-color: rgba(255, 255, 255, 0.5);
  user-select: none;
  cursor: pointer;
  opacity: 1;
}

.delet:hover {
  background-color: rgba(31, 31, 31, 0.5);
  color: white;
}

.previewPic {
  height: 100%;
  width: 77%;
}
</style>